﻿using Core.SimpleTemp.Application;
using Core.SimpleTemp.Application.UserApp;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.SimpleTemp.Repositories.Internal;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Linq;
using System.Threading.Tasks;


namespace Core.SimpleTemp.Api.Api
{
    /// <summary>
    /// JG_STOPTimes
    ///</summary>
    [ApiExplorerSettings(GroupName = "Sys")]//swagger分类标签
    [Route("api/[controller]")]//路由说明
    [EnableCors("any")]//跨域规则
    [ApiController]//APi标识Controller
    [Authorize]//验证是否登录
    public class JG_STOPTimesController : CoreApiController
    {
        private readonly JG_STOPTimesService _service;
        private readonly CoreDBContext _coreDBContext;
        /// <summary>
        /// JG_STOPTimes
        ///</summary>
        public JG_STOPTimesController(JG_STOPTimesService service, CoreDBContext coreDBContext)
        {
            _service = service;
            _coreDBContext = coreDBContext;
        }

        #region 基础增删改查
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetList")]
        [PermissionFilter(nameof(JG_STOPTimesController) + "_" + nameof(JG_STOPTimesController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult>
            GetList(PagingModel<JG_STOPTimesDto>
                pagingQueryModel)
        {
            IPageModel<JG_STOPTimesDto>
                result;
            result = await _service.GetList(pagingQueryModel);
            foreach (var i in result.PageData)
            {
                switch (i.WarnType)
                {
                    case "01": i.FrequencyText= "每月执行1次，提前" + i.WarnDays + "天提醒";break;
                    case "02": i.FrequencyText = "每周执行1次，提前" + i.WarnDays + "天提醒";break;
                    case "03": i.FrequencyText = "每日执行1次，提前" + i.WarnDays + "天提醒";break;
                    default: i.FrequencyText = "未设置";break;
                }
               
            }
            return this.JsonSuccess(result);
        }

        

        /// <summary>
        /// 添加/修改
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Save")]
        [PermissionFilter(nameof(JG_STOPTimesController) + "_" + nameof(JG_STOPTimesController.SaveAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult>
            SaveAsync(JG_STOPTimesDto dto)
        {


            var userinfo = _coreDBContext.SysUserInfor.FirstOrDefault(x => x.SysUserID == dto.name);

            dto.CreateFactory = userinfo.WorkCompany;
            
            var userDepaDuty = _coreDBContext.SysUserDepartmentDuty.FirstOrDefault(x => x.SysUserInforID == userinfo.Id);

            var userDuty = _coreDBContext.SysUserDuty.FirstOrDefault(x => x.SysUserId == dto.name);
            var departmentDuty = _coreDBContext.SysDepartmentDuty.FirstOrDefault(x => x.Id == userDuty.SysDepartmentDutyId);
            

            if (departmentDuty != null)
            {
                dto.department = departmentDuty.SysDepartmentID;
                dto.duty = departmentDuty.SysDutyID;
            }
            //添加
            if (Equals(dto.Id, Guid.Empty))
            {
                //检查是否已经存在相同用户的记录
                var existedUser = _coreDBContext.JG_STOPTimes.FirstOrDefault(x => x.IsDeleted == false && x.name == dto.name);
                if (existedUser != null)
                {
                    return this.JsonFaild("该用户记录已经存在");
                }
                await _service.InsertAsync(dto);
                return this.JsonSuccess(string.Empty);
            }
            else
            {
                await _service.UpdateAsync(dto);
                return this.JsonSuccess(string.Empty);
            }
        }

        /// <summary>
        /// DeleteMuti
        ///</summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMuti")]
        [PermissionFilter(nameof(JG_STOPTimesController) + "_" + nameof(JG_STOPTimesController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult>
            DeleteMutiAsync([FromBody]Guid[] ids)
        {

            await _service.DeleteBatchAsync(ids);
            return this.JsonSuccess();
        }


        /// <summary>
        /// 根据ID获取信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("Get")]
        public async Task<IActionResult>
            Get(Guid id)
        {
            var model = await _service.GetAsync(id);
            if (model == null) return this.JsonFaild("未找到对应数据:" + id);
            return this.JsonSuccess(model);
        }


        /// <summary>
        /// 导出
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("Export")]
        [PermissionFilter(nameof(JG_STOPTimesController) + "_" + nameof(JG_STOPTimesController.Export), AuthorizationConst.EXPORT)]
        public async Task<IActionResult>
            Export(PagingModel<JG_STOPTimesDto>
                pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            if (string.IsNullOrWhiteSpace(fileName))
                return this.JsonFaild(NULL_DATA_FOR_EXCEL_EXPORT);
            return this.JsonSuccess(fileName);
        }
        #endregion


        #region by songyf
        /// <summary>
        /// 获得当前登录用户所在工厂的Guid
        /// </summary>
       
        /// <returns></returns>
        [HttpGet("GetCurrentUserFactory")]
        public async Task<IActionResult> GetCurrentUserFactory()
        {
            var id = UserIdentity.Id;
            var dto = await _service.TestService(id);
            var rtn =dto.SysUserInfor.WorkCompany;
            return this.JsonSuccess(rtn);
           
        }

        /// <summary>
        /// 获得人名列表
        /// </summary>
        /// <param name="departmentId"></param>
        /// <param name="dutyId"></param>
        /// <returns></returns>
        [HttpGet("GetNames")]
        public async Task<IActionResult> GetNames(Guid departmentId,Guid dutyId)
        {
            var userDepartmentDutys = await _coreDBContext.SysUserDepartmentDuty.Where(x => x.SysDepartmentID == departmentId && x.SysDutyID == dutyId).ToListAsync();
            var userIds = userDepartmentDutys.Select(a => a.SysUserInforID);
            var users = _coreDBContext.SysUserInfor.Where(a => userIds.Contains(a.SysUserID)).ToList();
            var returnModel = new
            {
                users
            };
            return this.JsonSuccess(returnModel);

        }

        #endregion

    }
}
